//
//  ProjectsViewController.m
//  YYZB
//
//  Created by 顾悦 on 16/3/30.
//
//

#import "ProjectsViewController.h"

#import "ProjectTableViewCell.h"
#import "MyHelperCollectionViewCell.h"

#import "ProjectWebService.h"

#import "ProjectCategory.h"

#import "UIImageView+OnlineImage.h"
#import "SVPullToRefresh.h"

#import "ClientWebViewController.h"
#import "BulkOrderViewController.h"

@interface ProjectsViewController () <UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (strong, nonatomic) NSArray<ProjectCategory *> *categories;
@property (strong, nonatomic) NSArray<Project *> *items;
@property (nonatomic) NSUInteger pageIndex;
@property (nonatomic) NSUInteger pageSize;

@property (strong, nonatomic) ProjectWebService *projectWebService;

@property (strong, nonatomic) ProjectCategory *selectedCategory;

@end

@implementation ProjectsViewController

#pragma mark - 

- (void)setTableView:(UITableView *)tableView {
    _tableView = tableView;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
}

- (void)setCollectionView:(UICollectionView *)collectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/3, 160);
    
    _collectionView.collectionViewLayout = layout;
    _collectionView = collectionView;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[MyHelperCollectionViewCell class] forCellWithReuseIdentifier:@"MyitemCell"];
}

#pragma mark - 

- (ProjectWebService *)projectWebService {
    if (!_projectWebService) {
        _projectWebService = ProjectWebService.new;
    }
    
    return _projectWebService;
}

- (ProjectCategory *)selectedCategory {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    return self.categories[indexPath.row];
}
//
//- (NSUInteger)pageIndex {
//    if (_pageIndex == 0) {
//        _pageIndex = 1;
//    }
//    
//    return _pageIndex;
//}

- (NSUInteger)pageSize {
    if (_pageSize == 0) {
        _pageSize = 100;
    }
    
    return _pageSize;
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.serviceName;
    if (self.menuData) {
        ProjectCategory *data = [[ProjectCategory alloc] init];
        data.ID = self.menuData.ServiceCat2Id;
        data.name = self.menuData.ModuleName;
        self.selectedCategory = data;
        self.categories = [NSMutableArray arrayWithObject:data];
        [self.tableView reloadData];
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
        [self fetchItems];
    } else {
        [self fetchProjectCategories];
    }
    [self setupInfiniteScrolling];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.categories count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProjectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"categoryCell" forIndexPath:indexPath];
    
    ProjectCategory *c = self.categories[indexPath.row];
    cell.nameLabel.text = c.name;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self fetchItems];
}

#pragma mark -

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.items count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MyHelperCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyitemCell" forIndexPath:indexPath];
    
    Project *p = self.items[indexPath.item];
    [cell fillData:p];
//    
//    [cell.imageView888 setOnlineImage:p.imagePath];
//    cell.nameLabel.text = p.name;
//    NSString *format = @"¥%@";
//    if ([p.paymentType integerValue] == 2) {
//        format = [format stringByAppendingString:p.unitExtend];
//    }
//    cell.priceLabel.text = [NSString stringWithFormat:format, p.price];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGRect bounds = collectionView.bounds;
    if (bounds.size.width > 260) {
        return CGSizeMake(bounds.size.width / 3, 160.0);
    } else {
        return CGSizeMake(bounds.size.width / 2, 160.0);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    Project *p = self.items[indexPath.row];
    if (self.delegate) {
        [self.delegate didSelectProject:p];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        
        //发版本 暂时去掉团购这块
        if (p.isGroupBy == 1) { //如果是团购商品则跳转团购列表页面
            BulkOrderViewController *vc = [[BulkOrderViewController alloc] init];
//            vc.hidesBottomBarWhenPushed = YES;
            vc.title = @"团购列表";
            vc.groupBuyingId = p.serviceProgramPriceID;
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
        
    
        ClientWebViewController *webViewController = ClientWebViewController.new;
//        if (self.bizType == BizTypeMaintain) {
//            webViewController.HTMLURL = [NSString stringWithFormat:@"projects/projectDetail.html?id=%@&pid=%@&cate=wx", p.ID, p.serviceProgramPriceID];
//        } else if (self.bizType == BizTypeCarWash) {
//            webViewController.HTMLURL = [NSString stringWithFormat:@"projects/projectDetail.html?id=%@&pid=%@&cate=xc", p.ID, p.serviceProgramPriceID];
//        } else if (self.bizType == BizTypeSchool) {
//            webViewController.HTMLURL = [NSString stringWithFormat:@"projects/projectDetail.html?id=%@&pid=%@&cate=jj", p.ID, p.serviceProgramPriceID];
//        } else if (self.bizType == BizTypeHouse) {
//            webViewController.HTMLURL = [NSString stringWithFormat:@"projects/projectDetail.html?id=%@&pid=%@&cate=jz", p.ID, p.serviceProgramPriceID];
//        } else if (self.bizType == BizTypeDecoration) {
//            webViewController.HTMLURL = [NSString stringWithFormat:@"projects/projectDetail.html?id=%@&pid=%@&cate=decoration", p.ID, p.serviceProgramPriceID];
//        } else {
        webViewController.HTMLURL = [NSString stringWithFormat:@"../projects/projectDetail.html?id=%@&pid=%@&cate1Id=%@", p.ID, p.serviceProgramPriceID, p.serviceID];
        webViewController.title = @"项目详情";
//        }
        [self.navigationController pushViewController:webViewController animated:YES];
    }
}

#pragma mark -

- (NSInteger)toSelectCategoryIndex {
    __block NSInteger r = 0;
    [self.categories enumerateObjectsUsingBlock:^(ProjectCategory * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([[obj.ID uppercaseString] isEqualToString:[self.serviceSubCategoryID uppercaseString]]) {
            *stop = YES;
            r = idx;
        }
    }];
    return r;
}

- (void)fetchProjectCategories {
    [LoadingView show];
    [self.projectWebService getCategoriesByServiceID:self.serviceID completionHanlder:^(NSArray *items, NSError *error) {
        [LoadingView dismiss];
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
            NSMutableArray<ProjectCategory *> *cs = NSMutableArray.new;
            for (NSDictionary *i in items) {
                [cs addObject:[[ProjectCategory alloc] initWithDictionary:i]];
            }
            if (self.serviceSubCategoryID.length > 0) {
                self.categories = cs;
                self.categories = @[self.categories[[self toSelectCategoryIndex]]];
            } else {
                ProjectCategory *all = [[ProjectCategory alloc] initWithID:@"" name:@"全部"];
                [cs insertObject:all atIndex:0];
                self.categories = cs;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                if ([self.categories count] > 0) {
                    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
                    [self fetchItems];
                }
            });
        }
    }];
}

- (void)fetchItems {
    [self fetchItemsPagingEnabled:NO];
}

- (void)fetchItemsPagingEnabled:(BOOL)flag {
    if (!flag) {
        self.pageIndex = 0;
    }
    [LoadingView show];
    [self.projectWebService getProjectsByServiceID:self.serviceID categoryID:self.selectedCategory.ID communityId:self.communityId pageIndex:@(self.pageIndex + 1) pageSize:@(self.pageSize) completionHanlder:^(NSArray *items, NSError *error) {
        [LoadingView dismiss];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView.infiniteScrollingView stopAnimating];
        });
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
            NSMutableArray<Project *> *ps = NSMutableArray.new;
            for (NSDictionary *i in items) {
                [ps addObject:[[Project alloc] initWithDictionary:i]];
            }
            if (flag) {
                self.items = [[self.items arrayByAddingObjectsFromArray:ps] mutableCopy];
            } else {
                self.items = ps;
            }
            self.pageIndex ++;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            self.noDataView.hidden = self.items.count;
        });
    }];
}

- (void)setupInfiniteScrolling {
    [self.collectionView addInfiniteScrollingWithActionHandler:^{
        [self loadMoreInfos];
    }];
}

- (void)loadMoreInfos {
    [self fetchItemsPagingEnabled:YES];
}

@end
